package com.example.hcbmsm.service.impl;

import com.auth0.jwt.interfaces.Claim;
import com.example.hcbmsm.domain.*;
import com.example.hcbmsm.mapper.PreDrugMapper;
import com.example.hcbmsm.mapper.PreMapper;
import com.example.hcbmsm.service.*;
import com.example.hcbmsm.util.HCBMSMResult;
import com.example.hcbmsm.util.JavaWebToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author Xinghm
 * @version 1.0
 * @since 2024/11/1 16:32
 */
@Service
public class PreDrugServiceImpl implements PreDrugService {
    @Autowired
    private PreDrugMapper preDrugMapper;
    @Autowired
    private InvService invService;
    @Autowired
    private OutboundService outboundService;
    @Autowired
    private DrugService drugService;
    @Autowired
    private OpService opService;
    @Autowired
    private PreService preService;

    @Override
    public Map add(String token, PreDrug preDrug) {
        Long drugId = preDrug.getDrugId();
        Inv inv = invService.getDrugAmount(drugId);
        if (inv.getInvAmount() < preDrug.getDrugNum()) {
            return HCBMSMResult.ERROR("库存不足");
        }
        if (preDrugMapper.insertSelective(preDrug) == 1) {
            inv.setInvAmount(inv.getInvAmount() - preDrug.getDrugNum());
            invService.renew(inv);
            Map<String, Claim> tokenInfo = JavaWebToken.getTokenInfo(token);
            Long docId = new Long(tokenInfo.get("docId").asString());
            Outbound outbound = new Outbound();
            outbound.setInvId(inv.getInvId());
            outbound.setDocId(docId);
            outbound.setOutboundNumber(preDrug.getDrugNum());
            outboundService.add(outbound);
            List<PreDrug> preDrugs = preDrugMapper.selectByPreId(preDrug.getPreId());
            double totalPrice = 0;
            for (PreDrug preDrug1 : preDrugs) {
                Drug drug = drugService.getDrug(preDrug1.getDrugId());
                totalPrice += drug.getDrugPrice() * preDrug1.getDrugNum();
            }
            Pre pre = preService.getPre(preDrug.getPreId());
            Op op = new Op();
            op.setOpId(pre.getOpId());
            op.setOpMoney((int) totalPrice);
            opService.renew(op);
            return HCBMSMResult.SUCCESS();
        }
        return HCBMSMResult.ERROR();
    }

    @Override
    public Map listByPreId(Long preId) {
        return HCBMSMResult.SUCCESS(preDrugMapper.selectByPreId(preId));
    }
}
